package devicelogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpDeviceStateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpDeviceStateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpDeviceStateLogic {
	return &UpDeviceStateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpDeviceStateLogic) UpDeviceState(in *iotpb.UpDeviceStateReq) (*iotpb.UpDeviceStateResp, error) {
	one, err := l.svcCtx.IotDeviceModel.FindOne(l.ctx, in.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update device state"), err, in)
	}

	one.State = in.GetState()
	one.UpdateUser = in.GetUpdateUser()

	// 更新
	err = l.svcCtx.IotDeviceModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update device"), err, in)
	}

	return &iotpb.UpDeviceStateResp{}, nil
}
